<script setup>

import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import courseService from '@/services/courseService.js'
import { Picture, User, Coin, TrendCharts } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, ElRadioGroup, ElRadioButton } from 'element-plus';
import { userManager } from '@/utils/user.js';

const route = useRoute()
const router = useRouter()
const courses = ref([])
const loading = ref(false)
const message = ref('')
const currentUserId = ref(null);

const pagination = reactive({
  page: 1,
  pageSize: 12,
  total: 0
})

const queryParams = reactive({
  q: '',
  sortBy: 'default'
})

const purchaseCourse = (event, course) => {
  event.stopPropagation();
  const userId = userManager.getUserId();
  if (!userId) {
    ElMessage.error('无法获取用户ID，请先登录！');
    return;
  }
  ElMessageBox.confirm(
      `这将会花费 ${course.credit} 学分来购买课程 "${course.name}"。要继续吗？`,
      '课程购买确认',
      { confirmButtonText: '确定购买', cancelButtonText: '取消', type: 'warning' }
  ).then(async () => {
    try {
      const response = await courseService.selectCourse(course.id, userId);
      if (response.success) {
        ElMessage.success('课程购买成功！');
        const purchasedCourse = courses.value.find(c => c.id === course.id);
        if (purchasedCourse) {
          purchasedCourse.isJoined = true;
        }
        await search(pagination.page);
      } else {
        ElMessage.error(`购买失败: ${response.message}`);
      }
    } catch (error) {
      ElMessage.error('购买课程时发生网络错误，请稍后再试！');
    }
  }).catch(() => {
    ElMessage.info('已取消购买');
  });
};

const search = async (toPage = 1) => {
  loading.value = true
  message.value = ''
  pagination.page = toPage

  try {
    const params = { //
      q: queryParams.q, //
      page: pagination.page,
      size: pagination.pageSize,
      currentUserId: currentUserId.value
    };
    const res = await courseService.searchCourses(params);
    if (res.success && res.data.records.length > 0) {
      let sortedCourses = res.data.records;

      if (queryParams.sortBy === 'credit') {
        sortedCourses.sort((a, b) => b.credit - a.credit);
      }

      courses.value = sortedCourses;
      pagination.total = res.data.total;
    } else {
      courses.value = [];
      pagination.total = 0;
      message.value = '未找到相关课程';
    }
  } catch (e) {
    console.error('Search failed:', e);
    message.value = '搜索失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

const handleCardClick = (course) => {
  if (course.isJoined) {
    router.push(`/course/${course.id}`);
  } else {
    ElMessage.info('请先购买课程才能查看详情！');
  }
}
const handlePageChange = (newPage) => {
  search(newPage)
}

watch(() => queryParams.sortBy, () => {
  search(1);
})

watch(() => route.query.q, (newQuery) => {
  queryParams.q = newQuery || ''
  search(1)
}, { immediate: true })

onMounted(() => {
  currentUserId.value = userManager.getUserId();
  search(1);
})
</script>

<template>
  <div class="search-course-background">
    <div class="search-course-page">
      <aside class="left-sidebar">
        <div class="filter-group">
          <h3 class="filter-title">排序方式</h3>
          <el-radio-group v-model="queryParams.sortBy" class="sort-menu">
            <el-radio-button label="default">综合排序</el-radio-button>
            <el-radio-button label="credit">学分最高</el-radio-button>
          </el-radio-group>
        </div>
      </aside>

      <main class="right-content">
        <h2 v-if="queryParams.q" class="search-title">
          "{{ queryParams.q }}" 的搜索结果
        </h2>

        <div v-if="loading" class="loading-state"></div>
        <el-empty v-else-if="!loading && courses.length === 0" :description="message || '暂无课程'" style="margin-top: 48px;" />

        <div v-else class="results-grid">
          <el-row :gutter="28">
            <el-col :xs="24" :sm="12" :md="8" v-for="course in courses" :key="course.id" class="course-col">
              <div :class="['course-card', { 'is-clickable': course.isJoined }]" @click="handleCardClick(course)">
                <div class="course-image-wrapper">
                  <el-image :src="course.image || ''" fit="cover" class="course-image">
                    <template #error><div class="image-slot-error"><el-icon><Picture /></el-icon></div></template>
                  </el-image>
                </div>
                <div class="card-body">
                  <h3 class="course-title" :title="course.name">{{ course.name }}</h3>
                  <div class="teacher-info">
                    <el-avatar :size="24" :src="course.teacherAvatar || 'https://creditbank.oss-cn-chengdu.aliyuncs.com/2025/07/02/d608cb75-1f1c-48d1-819c-03152564aa22.png'" :icon="User" class="teacher-avatar-small" />
                    <span>{{ course.teacherUsername || '匿名教师' }}</span>
                  </div>
                  <p class="course-description" :title="course.description">{{ course.description }}</p>
                  <div class="card-spacer"></div>
                </div>
                <div class="card-footer">
                  <div class="meta-info">
                    <span class="meta-item"><el-icon><Coin /></el-icon>{{ course.credit ?? 'N/A' }} 学分</span>
                  </div>
                  <div class="card-actions">
                    <el-button v-if="course.isJoined" type="success" size="small" plain disabled>已加入</el-button>
                    <el-button v-else type="primary" size="small" @click="purchaseCourse($event, course)">购买</el-button>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-pagination
              v-if="pagination.total > pagination.pageSize"
              class="pagination-center"
              background
              layout="prev, pager, next"
              :total="pagination.total"
              :page-size="pagination.pageSize"
              :current-page="pagination.page"
              @current-change="handlePageChange"
          />
        </div>
      </main>
    </div>
  </div>
</template>

<style scoped>
.search-course-background { background: linear-gradient(180deg, #f8f9fb 0%, #f4f6f9 100%); min-height: 100vh; }
.search-course-page { display: flex; gap: 32px; max-width: 1300px; margin: 0 auto; padding: 24px; align-items: flex-start; }
.left-sidebar { width: 220px; flex-shrink: 0; position: sticky; top: 24px; }
.right-content { flex: 1; min-width: 0; }
.filter-title { font-size: 1rem; font-weight: 500; color: #3c4043; margin: 0 0 16px 8px; }
.sort-menu { display: flex; flex-direction: column; width: 100%; }
.sort-menu :deep(.el-radio-button__inner) { width: 100%; border-radius: 8px !important; border: none; background: none; text-align: left; padding: 10px 12px; font-size: 14px; color: #3c4043; transition: background-color 0.2s, color 0.2s; }
.sort-menu :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) { background-color: var(--el-color-primary-light-9); color: var(--el-color-primary); font-weight: 600; }
.search-title { font-size: 1.5rem; font-weight: 500; color: #202124; margin-bottom: 24px; }
.results-grid { display: flex; flex-direction: column; gap: 24px; }
.pagination-center { margin-top: 32px; display: flex; justify-content: center; }

/* 核心修正：为列增加下边距，形成垂直间距 */
.course-col {
  margin-bottom: 28px;
}

/* 课程卡片 */
.course-card { background-color: #fff; border-radius: 16px; box-shadow: 0 1px 2px 0 rgba(60,64,67,0.3), 0 2px 6px 2px rgba(60,64,67,0.15); transition: box-shadow 0.3s ease; cursor: pointer; display: flex; flex-direction: column; height: 100%; overflow: hidden; position: relative; }
.course-card::after { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.03); opacity: 0; transition: opacity 0.3s ease; pointer-events: none; }
.course-card:hover::after { opacity: 1; }

/* 核心修正：调整图片长宽比，降低卡片高度 */
.course-image-wrapper { width: 100%; padding-top: 50%; /* 2:1 ratio */ position: relative; }
.course-image { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; }
.image-slot-error { display: flex; align-items: center; justify-content: center; height: 100%; background-color: #f1f3f4; color: #bdc1c6; font-size: 32px; }

.card-body { padding: 16px; display: flex; flex-direction: column; flex-grow: 1; }
/* 核心修正：微调排版 */
.course-title { font-size: 1.05rem; font-weight: 500; color: #202124; margin: 0 0 4px 0; line-height: 1.4; height: 2.8em; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
.teacher-info { font-size: 0.8rem; color: #5f6368; display: flex; align-items: center; gap: 6px; margin-bottom: 12px; }
.course-description { display: none; } /* 描述信息在卡片中不再显示，让卡片更紧凑 */
.card-spacer { flex-grow: 1; }

.card-footer { padding: 12px 16px; border-top: 1px solid #f0f0f0; margin-top: 12px; display: flex; justify-content: space-between; align-items: center; }
.meta-info { display: flex; flex-wrap: wrap; gap: 12px; font-size: 0.8rem; color: #5f6368; align-items: center;}
.meta-item { display: flex; align-items: center; gap: 4px; }

/* 响应式 */
@media (max-width: 768px) {
  .search-course-page { flex-direction: column; }
  .left-sidebar { position: static; width: 100%; margin-bottom: 24px; }
}
</style>